package com.ruoyi.activiti.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.activiti.domain.BizProcessInstanceRelation;
import com.ruoyi.activiti.domain.BookBorrow;
import com.ruoyi.activiti.mapper.BookBorrowExtMapper;
import com.ruoyi.activiti.service.IBizProcessInstanceRelationService;
import com.ruoyi.activiti.service.IProcessService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.TaskInfo;

/**
 * 书籍借阅Service业务层处理
 * 
 * @author wushi
 * @date 2024-11-19
 */
@Service
public class BookBorrowServiceExtImpl extends BookBorrowServiceImpl
{
    @Autowired
    private BookBorrowExtMapper bookBorrowMapper;

    @Resource
    private IProcessService processService;

    @Resource
    private IBizProcessInstanceRelationService bizProcessInstanceRelationService;
    public void submitApply(BookBorrow bookBorrow, String applyUserId, String processKey, HashMap<String, Object> variables) {
        ProcessInstance processInstance = processService.submitApply(applyUserId, String.valueOf(bookBorrow.getId()), bookBorrow.getTitle(), null, processKey, variables);

        //保持流程instanceId與業務表關係入庫
        BizProcessInstanceRelation bizProcessInstanceRelation = new BizProcessInstanceRelation();
        bizProcessInstanceRelation.setProcessInstanceId(processInstance.getId());
        bizProcessInstanceRelation.setBizId(String.valueOf(bookBorrow.getId()));
        bizProcessInstanceRelation.setCreateTime(new Date());
        bizProcessInstanceRelationService.insertBizProcessInstanceRelation(bizProcessInstanceRelation);
    }

    public List<BookBorrow> queryDoneTasks(String userId, String processKey) {
        List<HistoricTaskInstance> doneTasks = processService.findDoneTasks(userId, processKey);

        List<String> processInstances = doneTasks.stream().map(TaskInfo::getProcessInstanceId).collect(Collectors.toList());
        List<BizProcessInstanceRelation> bizProcessInstanceRelations = bizProcessInstanceRelationService.selectBizProcessInstanceRelationByIds(processInstances);

        List<String> bizIds = bizProcessInstanceRelations.stream().map(BizProcessInstanceRelation::getBizId).collect(Collectors.toList());
        List<BookBorrow> bookBorrows = bookBorrowMapper.selectBookBorrowByIds(bizIds);

        return bookBorrows;
    }
}
